<template>
	<view class="content">
		<!-- <button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
		   <image class="avatar" mode="aspectFit" :src="userInfo.headUrl"></image>
		</button> -->
		<button class="avatar-wrapper" @click="uploadHeadUrl">
		   <image class="avatar" mode="aspectFit" :src="headUrl"></image>
		</button>
		
		<view class="info-view">
			<view class="title">手机号：</view>
			<input class="info-input" type="number" placeholder="请输入手机号" v-model="userInfo.phone"/>
		</view>
		
		<view class="info-view">
			<view class="title">昵称：</view>
			<input class="info-input" type="nickname" @change="getNickname" placeholder="请输入昵称" v-model="userInfo.nickname"/>
		</view>
		
		<view class="info-view">
			<view class="title">性别：</view>
			<input class="info-input" placeholder="请选择性别" v-model="sex" @click="chooseSex"/>
		</view>
		
		<button class="add-btn" @click="save">保存</button>
	</view>
</template>

<script>
    // 引入后端接口函数
    import http from "@/api/backend.js";

    var _self; // 用于在函数内部访问组件实例

    export default {
        // 当组件创建时执行，保存组件实例
        created() {
            _self = this;
        },
        data() {
            return {
                phone: '',
                sex: '',
                headUrl: '',
                userInfo: {},  // 存储用户信息
                sexList: ['男', '女']  // 性别选择列表
            }
        },
        // 页面加载时执行，从本地存储获取用户信息并请求用户数据
        onLoad() {
            const userInfo = uni.getStorageSync('userInfo');
            this.userInfo = userInfo;
            this.getUserInfo();
        },
        onShow() {
            // 页面显示时触发的生命周期函数，此处未用到
        },
        methods: {
            // 选择头像功能，根据平台区分不同的实现
            choseImg() {
                uni.chooseImage({
                    count: 1,
                    sizeType: ['original', 'compressed'],
                    success: function(res) {
                        // 处理图片选择成功的情况
                    }
                });
            },
            // 上传头像，仅在小程序平台有效
            uploadHeadUrl() {
                uni.chooseImage({
                    count: 1,
                    sizeType: ['original', 'compressed'],
                    success: function(res) {
                        console.log(res);
                        let arr = res.tempFiles;
                        // 检查图片大小
                        for (let i = 0; i < arr.length; i++) {
                            if (arr[i].size > 10458760) { // 图片大小限制
                                uni.showToast({
                                    title: "图片过大",
                                    icon: 'error'
                                });
                                return;
                            }
                        }
                        uni.showLoading({title: "上传中"});
                        http.uploadFile(res.tempFilePaths).then(picRes => {
                            _self.headUrl = picRes[0];
                            _self.userInfo.avatarUrl = picRes[0];
                            uni.hideLoading();
                            uni.showToast({title: "上传成功", icon: 'success'});
                        })
                    }
                })
            },
            // 选择性别
            chooseSex() {
                uni.showActionSheet({
                    itemList: this.sexList,
                    success: function (res) {
                        _self.sex = res.tapIndex === 0 ? '男' : '女';
                        _self.userInfo.gender = res.tapIndex;
                    },
                    fail: function (res) {
                        console.log(res.errMsg);
                    }
                });
            },
            // 保存用户信息
            save() {
                http.updateUser(this.userInfo).then((res) => {
                    if (res.code != 0) {
                        uni.showToast({title: res.msg, icon: 'error'});
                        return;
                    }
                    uni.showToast({title: '保存成功', icon: 'success'});
                    uni.setStorageSync('userInfo', this.userInfo);
                    setTimeout(() => {
                        uni.navigateBack({delta: 1});
                    }, 1000);
                });
            },
            // 获取当前用户信息
            getUserInfo() {
                http.getUserInfo({openId: this.userInfo.openId}).then((res) => {
                    if (res.code != 0) {
                        uni.showToast({title: res.msg, icon: 'error'});
                        return;
                    }
                    this.userInfo = res.data;
                    this.headUrl = res.data.avatarUrl;
                    this.sex = res.data.gender == '0' ? '男' : '女';
                });
            },
            // 获取用户昵称输入
            getNickname: function (e) {
                this.userInfo.nickname = e.detail.value;
            }
        }
    }
</script>


<style lang="less">
	.content {
		padding: 20upx;
	}
	
	.avatar-wrapper {
		width: 110upx;
		height: 110upx;
		margin-top: 30upx;
		margin-bottom: 70upx;
		
		image {
			width: 110upx;
			height: 110upx;
			margin-left: -30upx;
		}
	}
	
	.info-view {
		height: 36px;
		
		.title {
			float: left;
			width: 20%;
		}
		
		.info-input {
			float: left;
			text-align: right;
			width: 80%;
		}
		
	}
	
	.add-btn {
		width: 160upx;
		height: 60upx;
		background-color: #64ADFF;
		color: #ffffff;
		line-height: 60upx;
		font-size: 30upx;
		margin-top: 40px;
	}
</style>